package com.pgyl.contract.service.base;

import com.pgyl.contract.service.ContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.pgyl.contract.model.Contract;

@Component
public class ContractServiceFactory {

    private final Map<Class<? extends Contract>, ContractService<?>> serviceMap;

    @Autowired
    public ContractServiceFactory(List<ContractService<?>> services) {
        serviceMap = services.stream()
            .filter(service -> service instanceof AbstractContractService)
            .collect(Collectors.toMap(
                service -> ((AbstractContractService<?>) service).getContractType(),
                Function.identity()
            ));
    }

    @SuppressWarnings("unchecked")
    public <T extends Contract> ContractService<T> getService(T contract) {
        ContractService<?> service = serviceMap.get(contract.getClass());
        if (service == null) {
            throw new IllegalArgumentException("未找到对应的服务处理");
        }
        return (ContractService<T>) service;
    }
}
